package com.ningmengs789.live.ui.widget;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 类 名: TabFragmentAdapter
 * 作 者: yzhg
 * 创 建: 2018/9/6 0006
 * 版 本: 1.0
 * 历 史: (版本) 作者 时间 注释
 * 描 述:
 */
public class TabFragmentAdapter extends FragmentPagerAdapter {

    private List<String> tags;//标示fragment的tag
    private Fragment[] fragments;
    private FragmentManager fragmentManager;
    private List<String> list_Title;

    public TabFragmentAdapter(FragmentManager fm, Fragment[] fragments, List<String> list_Title) {
        super(fm);
        this.tags = new ArrayList<>();
        this.fragmentManager = fm;
        this.fragments = fragments;
        this.list_Title = list_Title;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments[position];
    }

    @Override
    public int getCount() {
        return fragments.length;
    }


    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }


    private String makeFragmentName(int viewId, long id) {
        return "android:switcher:" + viewId + ":" + id;
    }

    @Override
    public void setPrimaryItem(@NonNull @NotNull ViewGroup container, int position, @NonNull @NotNull Object object) {
        super.setPrimaryItem(container, position, object);
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return  list_Title.get(position);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
    }

    //必须重写此方法，添加tag一一做记录
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        tags.add(makeFragmentName(container.getId(), getItemId(position)));
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        this.fragmentManager.beginTransaction().show(fragment).commitAllowingStateLoss();
        return fragment;
    }

    //根据tag查找缓存的fragment，移除缓存的fragment，替换成新的
    public void setNewFragments() {
        if (this.tags != null) {
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            for (int i = 0; i < tags.size(); i++) {
                fragmentTransaction.remove(Objects.requireNonNull(fragmentManager.findFragmentByTag(tags.get(i))));
            }
            fragmentTransaction.commit();
            fragmentManager.executePendingTransactions();
            tags.clear();
        }
        notifyDataSetChanged();
    }

}
